package com.yeyks.rocketmq.service.customer;

import cn.hutool.json.JSONUtil;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeyks.common.dto.mq.GrabTheOrderCheckMessage;
import com.yeyks.commonReference.service.order.OrderHeadService;
import com.yeyks.commonReference.service.order.OrderPickRecordService;
import com.yeyks.commonReference.service.order.OrderPubRecordService;
import com.yeyks.order.dal.domain.OrderHead;
import com.yeyks.order.dal.domain.OrderPickRecord;
import com.yeyks.order.dal.domain.OrderPubRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author fuchangshuai
 * @date 2019/08/09 16:06
 */
@Slf4j
@Component
public class CToWebOrderCheckListener implements MessageListener {
    @Autowired
    private OrderHeadService orderHeadService;
    @Autowired
    private OrderPickRecordService orderPickRecordService;
    @Autowired
    private OrderPubRecordService orderPubRecordService;
    @Autowired
    private CommonSendService commonSendService;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        try {
            Long startTime = System.currentTimeMillis();
            byte[] body = message.getBody();
            //获取到接收的消息，由于接收到的是byte数组，所以需要转换成字符串
            String msg = new String(body);
            //处理业务逻辑
            disposeLogic(msg);
            log.info("延迟抢单：监听到的消息：message = {}", msg);
            Long endTime = System.currentTimeMillis();
            log.info("延迟抢单：单次消费耗时：" + (endTime - startTime) / 1000);
        } catch (Exception e) {
            log.error("MessageListener.consume error:" + e.getMessage(), e);
        }
        log.info("MessageListener.Receive message");
        //如果想测试消息重投的功能,可以将Action.CommitMessage 替换成Action.ReconsumeLater
        return Action.CommitMessage;
    }

    /**
     * 处理监听逻辑
     *
     * @param msg
     */
    private void disposeLogic(String msg) {
        try {
            GrabTheOrderCheckMessage checkMessage = JSONUtil.toBean(msg, GrabTheOrderCheckMessage.class);
            if (null == checkMessage) {
                log.info("延迟抢单：监听到的消息为空msg = {}", msg);
                return;
            }
            //通过抢单记录表id获取抢单记录
            OrderPubRecord pubRecord = orderPubRecordService.getById(checkMessage.getOrderPubRecordId());
            if (null == pubRecord) {
                log.info("延迟抢单：通过抢单记录表id获取抢单记录为空id = {}", checkMessage.getOrderPubRecordId());
                return;
            }
            //通过用户id和时间戳(模糊)查询是否有订单，有订单不操作，没订单操作
            OrderHead orderHead = orderHeadService.getOne(new QueryWrapper<OrderHead>().eq(OrderHead.USER_ID, pubRecord.getUserId())
                    .like(OrderHead.EXTRA_INFO, pubRecord.getTimestamp()).last("limit 1"));
            if (null != orderHead) {
                log.info("延迟抢单：通过抢单记录表id已下单id = {}", checkMessage.getOrderPubRecordId());
                return;
            }
            //通过时间戳和用户id查询手动抢单的酒店
            List<OrderPickRecord> orderPickRecords = orderPickRecordService.list(new QueryWrapper<OrderPickRecord>().eq(OrderPickRecord.USER_ID, pubRecord.getUserId())
                    .eq(OrderPickRecord.TIMESTAMP, pubRecord.getTimestamp()).eq(OrderPickRecord.MANUAL_PICK_ORDER, 1));
            if (null == orderPickRecords || orderPickRecords.size() == 0) {
                log.info("延迟抢单：通过抢单记录表id获取抢单记录为空id = {}", checkMessage.getOrderPubRecordId());
                return;
            }
            commonSendService.sendFailMessage(orderPickRecords, null);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("延迟抢单：处理监听消息异常：msg = {}", msg);
        }
    }
}
